const axios = require('axios');

// 微信小程序的 AppID 和 AppSecret
const appId = 'wxda16538bb5ad5719';
const appSecret = '0f5a5aa60ba664846ac1f59b8e0cf007';

// 云开发环境 ID
const envId = 'cloud1-0g37ybf285b2af98';

// 云函数名称
const functionName = 'quickstartFunctions';

// 获取 access_token
async function getAccessToken(appId, appSecret) {
  const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;
  try {
    const response = await axios.get(url);
    return response.data.access_token;
  } catch (error) {
    console.error('获取 access_token 失败:', error);
    throw error;
  }
}

// 调用云函数
async function callCloudFunction(accessToken, envId, functionName, event) {
  const url = `https://api.weixin.qq.com/tcb/invokecloudfunction?access_token=${accessToken}&env=${envId}&name=${functionName}`;

  try {
    const response = await axios.post(url, event);
	console.log(event);
    return response.data;
  } catch (error) {
    console.error('调用云函数失败:', error);
    throw error;
  }
}

// 主函数
async function main(event) {
	var result;
  try {
    // 获取 access_token
    const accessToken = await getAccessToken(appId, appSecret);

    // 调用云函数
    result = await callCloudFunction(accessToken, envId, functionName, event);
  } catch (error) {
    console.error('主函数执行失败:', error);
  }
  return result;
}
function bar () {
	return {foo : "bar"}
}

console.log(bar());
// main()
// 执行主函数
module.exports = main